<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-24
 * Time: 09:23
 */
namespace App\Models;

use App\Http\Controllers\Api\RolesController;
use Zizaco\Entrust\EntrustRole;
use DB;

class Role extends EntrustRole
{
    protected $fillable = [
        'name', 'display_name', 'description','temporary_json'
    ];

    public function getList($where)
    {
        $info = $this
            ->where('status',1)
            ->when(!empty($where['id']),function ($query) use ($where){
                $query->where('id',$where['id']);
            })
            ->when(!empty($where['display_name']),function ($query) use ($where){
                $query->where('display_name','like','%'.$where['display_name'].'%');
            })
            ->orderBy('id','desc')
            ->select([
                'id',
                'name',
                'display_name',
                'description',
                'created_at',
            ])
            ->paginate($where['page_size']);

        foreach ($info as $key=>$value){
            //查询选中的权限
            $per_role = DB::table('permission_role')->where('role_id',$value->id)->get(['permission_id']);
            $role_arr = [];
            foreach ($per_role as $kk=>$vv)
            {
                $role_arr[$kk] = $vv->permission_id;
            }

            //查询最低级
            $level = DB::table('permissions')->whereIn('id',$role_arr)->max('level');
            if(empty($level)){
                $info[$key]->quanxian = [];
            }else{
                //$info[$key]->quanxian = [];
                $info[$key]->quanxian = $this->itemPermissions($level,[],$role_arr);
            }
        }

        return $info;
    }


    /**
     * 权限获取
     * @param $level
     * @param array $temp
     * @param array $where
     * @return mixed
     */
    public function itemPermissions($level,$temp = [],$where = [])
    {
        if(empty($temp)){
            //最低级权限目录
            $pers = DB::table('permissions')
                ->where('level',$level)
                ->when(!empty($where),function ($query) use ($where){
                    $query->whereIn('id',$where);
                })
                ->get();
            foreach ($pers as $key=>$value)
            {
                $temp[$value->pid][$value->id]['id'] = (string)$value->id;
                $temp[$value->pid][$value->id]['pid'] = (string)$value->pid;
                $temp[$value->pid][$value->id]['title'] = $value->display_name;
            }

            if($level == 2){
                //递归循环上级
                return $this->itemPermissions($level-1,$temp,$where);
            }else{
                return $temp;
            }
        }else{
            //查询上级
            $pers = DB::table('permissions')
                ->where('level',$level)
                ->when(!empty($where),function ($query) use ($where){
                    $query->whereIn('id',$where);
                })
                ->get();

            $temp_now = [];
            foreach ($pers as $key=>$value)
            {
                //判断是否存在下级
                if(!empty($temp[$value->id])){
                    $temp_now[$value->pid][$value->id]['id'] = (string)$value->id;
                    $temp_now[$value->pid][$value->id]['pid'] = (string)$value->pid;
                    $temp_now[$value->pid][$value->id]['title'] = $value->display_name;
                    $temp_now[$value->pid][$value->id]['list'] = array_values($temp[$value->id]);
                }else{
                    $temp_now[$value->pid][$value->id]['id'] = (string)$value->id;
                    $temp_now[$value->pid][$value->id]['pid'] = (string)$value->pid;
                    $temp_now[$value->pid][$value->id]['title'] = $value->display_name;
                }
            }

            //判断是否到顶级
            if($level != 0){
                //继续递归
                return $this->itemPermissions($level-1,$temp_now,$where);
            }else{
                return $temp_now['0'];
            }
        }
    }

    public function addRoles($data)
    {
        $temp['name'] = $data['name'];
        $temp['display_name'] = $data['display_name'];
        $temp['description'] = $data['description'];
        $temp['temporary_json'] = $data['temporary_json'];

        $bool = $this->getRoles(['display_name'=>$data['display_name'],'status'=>'1'],['id']);
        if(!empty($bool)){
            return ['code'=>'0','message'=>'请不要重复添加角色'];
        }

        $info = $this->create($temp);
        if(empty($info)){
            return ['code'=>'0','message'=>'添加失败'];
        }

        $bool = $this->allocation($info,$data['ids_arr']);
        if($bool){
            return ['code'=>'1','message'=>'添加成功'];
        }else{
            return ['code'=>'0','message'=>'添加失败'];
        }
    }


    public function updRoles($data)
    {
        $roles = $this->getRoles(['id'=>$data['id']],['id']);
        $temp['name'] = $data['name'];
        $temp['display_name'] = $data['display_name'];
        $temp['description'] = $data['description'];
        $temp['temporary_json'] = $data['temporary_json'];
        if(!$this->where('id',$data['id'])->update($temp)){
            return ['code'=>'0','message'=>'修改失败'];
        }

        $bool = $this->allocation($roles,$data['ids_arr']);
        if($bool){
            return ['code'=>'1','message'=>'修改成功'];
        }else{
            return ['code'=>'0','message'=>'修改失败'];
        }
    }


    public function allocation($info,$per_ids)
    {
        return $info->perms()->sync($per_ids);
    }

    public function getRoles($where,$key)
    {
        return $this->where($where)->first($key);
    }
}
